<script setup lang="ts">
import type { FieldRule, FormInstance } from '@arco-design/web-vue'
import { Message, Tooltip } from '@arco-design/web-vue'
import { omit } from 'lodash-es'
import IconsQuestion from '~icons/icons/question'
// import useGroupArea from '@/views/site/hooks/useGroupArea'
// import useGroupArea from '@/views/cdn/node/node-list/hooks/useGroupArea'
import { addCdnNodeApi, getCdnGroupListApi } from '@/apis/modules/cdn'
// import { addApiNodeApi } from '@/apis/modules/node/node'
import {
  capacityOptions,
  diskFileSizeOptions,
  MaxSizeOptions,
  memoryFileSizeOptions,
} from '@/constants/cdn-node'

// defineProps<{
//   visible: boolean
// }>()

// const emit = defineEmits(['reload'])
const emits = defineEmits<IEmits>()
interface IEmits {
  (e: 'update:visible', value: boolean): void
  (e: 'refresh'): void
  (e: 'reload'): void
}
const visible = defineModel<boolean>({ required: true })
const formRef = ref<FormInstance>()
const saveLoading = ref(false)
const formState = reactive<FormDataType>({
  id: '',
  name: '',
  group_id: '',
  enable_resolve: false,
  cascade_level: 1,
  disk_configs: [
    {
      path: '',
      capacity: {
        value: 200,
        unit: 3,
      },
    },
  ],
  disk_single_file_limit: {
    value: 200,
    unit: 2,
  },
  memory_config: {
    mode: 1,
    max_capacity: {
      value: 1,
      unit: 2,
    },
    single_file_limit: {
      value: 4,
      unit: 2,
    },
  },
})

// const { areaListOptions, getOptions } = useGroupArea('region', {
//   immediate: false,
// })

// const unit = ref(2)
// const diskIndexSizeUnit = ref(2)

const rules = computed<Record<string, FieldRule>>(() => ({
  name: {
    required: true,
    validator(value, callback) {
      if (!value) {
        return callback('请输入节点名称')
      } else if (value.length < 4 || value.length > 32) {
        return callback('节点名称长度为4-32个字符')
      }
      callback()
    },
  },
  group_id: { required: true, message: '请选择节点分组' },
  enable_resolve: { required: true, message: '请选择是否启用解析' },
  // 内存-单文件最大大小
  // 'memory_config.single_file_limit.value': fileSizeRule(
  //   memoryFileSizeOptions,
  //   formState.memory_config.single_file_limit.unit,
  //   '请输入单文件最大大小',
  // ),
  // 内存-最大容量
  // 'memory_config.max_capacity.value': {
  //   required: false,
  //   validator(value, callback) {
  //     const max = getOptionsLabel(
  //       MaxSizeOptions,
  //       formState.memory_config.max_capacity.unit,
  //       'max',
  //     )
  //     if (formState.memory_config.mode !== 2) {
  //       // 模式不是2，不需要验证
  //       callback()
  //       return
  //     }
  //     if (!value) {
  //       return callback('请输入最大容量')
  //     }
  //     if (value > Number(max)) {
  //       return callback(`最大值为${max}`)
  //     }
  //     return callback()
  //   },
  // },
  //   fileSizeRule(
  //   MaxSizeOptions,
  //   formState.memory_config.max_capacity.unit,
  //   '请输入分配容量',
  // ),
  // 磁盘-单文件最大大小
  // 'disk_single_file_limit.value': fileSizeRule(
  //   diskFileSizeOptions,
  //   formState.disk_single_file_limit.unit,
  //   '请输入单文件最大大小',
  // ),
}))
// 检验目录是否重复
function hasDuplicates(arr) {
  return new Set(arr).size !== arr.length
}

async function handleSubmit() {
  const error = await formRef.value?.validate()
  if (error)
    return false

  // const symbol = diskOptions.find(item => item.value === unit.value)?.label
  // const index_symbol = indexSizeOptions.find(
  //   item => item.value === diskIndexSizeUnit.value,
  // )?.label
  if (hasDuplicates(formState.disk_configs.map(item => item.path))) {
    Message.error('存储目录不能重复')
    return false
  }
  const data = {
    ...omit(formState, ['cache_size']),
  }
  return addCdnNodeApi(data).then(() => {
    Message.success('保存成功')
    visible.value = false
    emits('reload')
    emits('update:visible', false)
  })
}

async function handleClose() {
  console.log('close')
  await formRef.value?.resetFields()
  formState.id = ''
  formState.name = ''
  formState.group_id = ''
  formState.enable_resolve = false
  formState.cascade_level = 1
  formState.disk_configs = [
    {
      path: '',
      capacity: {
        value: 200,
        unit: 3,
      },
    },
  ]
  formState.group_type = undefined
  formState.disk_single_file_limit = {
    value: 200,
    unit: 2,
  }
  formState.memory_config = {
    mode: 1,
    max_capacity: {
      value: 1,
      unit: 2,
    },
    single_file_limit: {
      value: 4,
      unit: 2,
    },
  }
  emits('update:visible', false)
}

const groupOptions = ref<LabelValue[]>([])

// 获取节点分组
async function getClusterList() {
  const res = await getCdnGroupListApi({ limit: 0 })
  const list = res.list ?? []

  groupOptions.value = list
    .map(item => ({ label: item.name!, value: item.id!, type: item.type }))
    .filter(Boolean)
}

async function setDefaultCache() {
  return new Promise((resolve) => {
    // const state = get(CACHE_PATH_AND_DISK_STORE)
    // if (!state?.cache_path) {
    // set(
    //   CACHE_PATH_AND_DISK_STORE,
    //   {
    //     cache_path: '/var/auth-cdn/cache',
    //     cache_size: 200,
    //     unit: 2
    //   },
    //   {
    //     maxAge: 90 * 60 * 60 * 24,
    //     path: '/'
    //   }
    // )

    // formState.value.cache_path = '/var/cdn/cache'
    // formState.value.cache_size = 200
    // unit.value = 2
    // }
    // else {
    //   formState.value.cache_path = state.cache_path
    //   formState.value.cache_size = state.cache_size
    //   unit.value = state.unit
    // }
    resolve(true)
  })
}
async function handleOpen() {
  getClusterList()
  setDefaultCache()
  return true
}

async function refreshGroupList() {
  await getClusterList()
  const groupExists = groupOptions.value.some(
    item => item.value === formState.group_id,
  )
  if (!groupExists) {
    formState.group_id = ''
    formState.group_type = undefined
  }

  Message.success('操作成功')
}

const tableColumn = buildColumns([
  // {
  //   title: '存储目录',
  //   slotName: 'ip',
  // },
  {
    title: () =>
      h('div', { class: 'flex gap-x-1 items-center' }, [
        h('span', { class: 'text-12px/22px' }, '存储目录'),
        h('span', { class: 'text-12px text-[#FA5566]' }, ' *'),
        h(
          Tooltip,
          {
            showArrow: false,
            class: 'border-radius-20px',
            contentStyle: {
              borderRadius: '12px !important',
            },
          },
          {
            default: () =>
              h(IconsQuestion, {
                class:
                  'question-icon text-#8F959E w-14px  h-14px hover:text-primary',
              }),
            content: () =>
              h(
                'span',
                {
                  class: 'text-12px',
                },
                [
                  '用于持久化缓存的磁盘存储目录（需设置目录所有者权限为 nobody）。',
                ],
              ),
          },
        ),
      ]),
    slotName: 'path',
    // render({ record }) {
    //   return record.cascade_level === 1 ? 'L1' : 'L2'
    // },
  },
  {
    title: () =>
      h('div', { class: 'flex gap-x-1 items-center' }, [
        h('span', { class: 'text-12px/22px' }, '分配容量'),
        h('span', { class: 'text-12px text-[#FA5566]' }, ' *'),
        h(
          Tooltip,
          {
            showArrow: false,
            class: 'border-radius-20px',
            contentStyle: {
              borderRadius: '12px !important',
            },
          },
          {
            default: () =>
              h(IconsQuestion, {
                class:
                  'question-icon text-#8F959E w-14px  h-14px hover:text-primary',
              }),
            content: () =>
              h(
                'span',
                {
                  class: 'text-12px',
                },
                ['为存储目录分配的存储容量。'],
              ),
          },
        ),
      ]),
    slotName: 'capacity',
    width: 160,
    // render({ record }) {
    //   return record.cascade_level === 1 ? 'L1' : 'L2'
    // },
  },
  {
    title: '操作',
    slotName: 'action',
    cellClass: 'actions-cell',
    width: 56,
  },
])

// 磁盘列表-存储目录
const catalogueRules: FieldRule = {
  required: true,
  validator: (value, callback) => {
    if (!value) {
      return callback('存储目录不能为空')
    }
    // if (!regexpMap.ipv4.test(value)) {
    //   return callback('存储目录格式不正确')
    // }
    callback()
  },
}
// 磁盘列表-分配容量
const sizeRules: FieldRule = {
  required: true,
  validator(value, callback) {
    // const max = getOptionsLabel(capacityOptions, unit, 'max')
    if (!value) {
      return callback('分配容量不能为空')
    }
    if (value > 999) {
      return callback(`最大值为999`)
    }
    callback()
  },
}
// 磁盘-单文件最大大小
const diskSingleFileLimitRules: FieldRule = {
  required: true,
  validator: (value, callback) => {
    const max = getOptionsLabel(
      diskFileSizeOptions,
      formState.disk_single_file_limit.unit,
      'max',
    )
    if (!value) {
      return callback('请输入单文件最大大小')
    }
    if (value > Number(max)) {
      return callback(`最大值为${max}`)
    }
    return callback()
  },
}

// 内存-单文件最大大小
const singleFileLimitRules: FieldRule = {
  required: true,
  validator: (value, callback) => {
    const max = getOptionsLabel(
      memoryFileSizeOptions,
      formState.memory_config.single_file_limit.unit,
      'max',
    )
    if (!value) {
      return callback('请输入单文件最大大小')
    }
    if (value > Number(max)) {
      return callback(`最大值为${max}`)
    }
    return callback()
  },
}

// 内存-最大容量
const singleMaxCapacityRules: FieldRule = {
  // required: formState.memory_config.mode === 2, // 只在手动模式下必填
  required: true,
  validator: (value, callback) => {
    if (formState.memory_config.mode !== 2) {
      return callback() // 非手动模式不验证
    }

    if (!value) {
      return callback('请输入最大容量')
    }

    const currentUnit = formState.memory_config.max_capacity.unit
    const max = getOptionsLabel(MaxSizeOptions, currentUnit, 'max')
    if (value > max) {
      return callback(`最大值为${max}`)
    }

    return callback()
  },
}

function handleTableCommand(command: string, index?: number) {
  const map: Record<string, any> = {
    add: () => {
      formState.disk_configs.push({
        path: '',
        capacity: {
          value: 200,
          unit: 3,
        },
      })
    },
    delete: () => {
      // formRef.value?.resetFields(`disk_configs[${index}].ip`)
      formState.disk_configs!.splice(index!, 1)
    },
    // set_main: () => {
    //   const mainIp = formState.disk_configs[index!]
    //   // formRef.value?.validateField(`disk_configs[${index}].ip`)
    //   if (!regexpMap.ipv4.test(mainIp.ip) || !mainIp.ip) {
    //     return ''
    //   } else {
    //     formState.disk_configs.splice(index!, 1)
    //     formState.disk_configs.unshift(mainIp)
    //   }
    // },
  }
  map[command] && map[command]()
}

function handleJump() {
  window.open('/cdn/node/group-management?type=open', '_target')
}

const selectedItem = computed(() => {
  return groupOptions.value.find(item => item.value === formState.group_id)
})

function groupTypeChange(item) {
  if (item) {
    formState.group_type = selectedItem.value?.type
  } else {
    formState.group_type = undefined
  }
}

function handleChangeFileSize(value) {
  formState.disk_single_file_limit.unit = value
  formRef.value?.validateField('disk_single_file_limit.value')
}
</script>

<template>
  <a-drawer
    :visible="visible"
    title="新建节点"
    :width="500"
    ok-text="保存"
    :mask-closable="false"
    :close-on-click-modal="false"
    :loading="saveLoading"
    @ok="handleSubmit"
    @open="handleOpen"
    @close="handleClose"
    @cancel="emits('update:visible', false)"
  >
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
    >
      <a-form-item
        label="节点名称"
        field="name"
        asterisk-position="end"
        hide-asterisk
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>节点名称</span>
            <span class="text-[#FA5566]">*</span>
          </div>
        </template>
        <a-input
          v-model="formState.name"
          :max-length="32"
          show-word-limit
          placeholder="请输入节点名称"
        />
      </a-form-item>
      <a-form-item
        label="节点分组"
        field="group_id"
        asterisk-position="end"
        hide-asterisk
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>节点分组</span>
            <span class="text-[#FA5566]">*</span>
          </div>
        </template>
        <a-select
          v-model="formState.group_id"
          placeholder="请选择节点分组"
          show-footer-on-empty
          @change="groupTypeChange"
        >
          <template #label="data">
            <span>{{ data.data.label }}</span>
            <span class="ml-1 text-12px text-[#8F959E]">
              {{ selectedItem?.type === 1 ? '(边缘组)' : '(上游组)' }}
            </span>
          </template>
          <a-option
            v-for="item in groupOptions"
            :key="item.value"
            :value="item.value"
            :label="item.label"
          >
            <span style="float: left">{{ item.label }}</span>
            <span class="ml-1 text-12px text-[#8F959E]">{{
              item.type === 1 ? '(边缘组)' : '(上游组)'
            }}</span>
          </a-option>
          <template #footer>
            <div
              class="h-8 flex cursor-pointer items-center gap-x-1 px-3 text-[#00A65B] leading-8"
              @click="handleJump"
            >
              <span class="text-xs leading-[19px]">新建分组</span>
              <i-icons-jump size="14px" />
            </div>
          </template>
        </a-select>
        <a-button
          class="ml-2 w-8"
          type="outline"
          @click="refreshGroupList"
        >
          <div class="w-8 flex items-center justify-center">
            <i-icons-refresh
              size="14px"
              class="h-14px! w-14px!"
            />
          </div>
        </a-button>
      </a-form-item>

      <a-form-item
        v-if="formState.group_type === 1"
        label="加入解析"
        field="enable_resolve"
        hide-asterisk
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>加入解析</span>
            <span class="text-[#FA5566]">*</span>
            <a-tooltip
              :content-style="{ 'max-width': '509px' }"
              :show-arrow="false"
            >
              <i-icons-question class="question-icon text-#86909C" />
              <template #content>
                <span>
                  1.立即加入，该节点将参与链路解析。
                  <br>
                  2.暂不加入，该节点则不会参与链路解析。
                </span>
              </template>
            </a-tooltip>
          </div>
        </template>
        <div class="w-full">
          <div class="h-8">
            <a-radio-group
              v-model="formState.enable_resolve"
              class="ml-2"
            >
              <a-radio :value="true">
                立即加入
              </a-radio>
              <a-radio :value="false">
                暂不加入
              </a-radio>
            </a-radio-group>
          </div>
        </div>
      </a-form-item>

      <a-divider
        type="dashed"
        margin="0"
      />

      <div class="node-sub-title mb-4 mt-6">
        磁盘配置
      </div>
      <a-form-item
        label=""
        field=""
        asterisk-position="end"
      >
        <a-table
          :columns="tableColumn"
          :data="formState.disk_configs"
          class="node-ip-table"
          :pagination="false"
        >
          <template #path="{ record, rowIndex }">
            <a-form-item
              :field="`disk_configs[${rowIndex}].path`"
              hide-asterisk
              hide-label
              :rules="catalogueRules"
              validate-trigger="blur"
            >
              <a-input
                v-model="record.path"
                placeholder="请确认目录所有者权限为 nobody"
              />
            </a-form-item>
          </template>
          <template #capacity="{ record, rowIndex }">
            <a-form-item
              :field="`disk_configs[${rowIndex}].capacity.value`"
              hide-asterisk
              hide-label
              :rules="sizeRules"
              validate-trigger="blur"
            >
              <a-input-number
                v-model="record.capacity.value"
                :controls="true"
                :precision="0"
                :min="1"
                :max-length="13"
                class="cloud-input-number"
                hide-button
                placeholder="请输入"
                :step="1"
              >
                <template #append>
                  <a-select
                    v-model="record.capacity.unit"
                    :options="capacityOptions"
                    class="rounded-tl-none rounded-bl-none! border-none! bg-transparent!"
                  />
                </template>
              </a-input-number>
            </a-form-item>
          </template>
          <template #action="{ rowIndex }">
            <a-link
              :hoverable="false"
              status="danger"
              :disabled="formState.disk_configs.length <= 1"
              @click="handleTableCommand('delete', rowIndex)"
            >
              <i-icons-delete size="16px" />
            </a-link>
          </template>
          <template #footer>
            <a-link
              class="cloud-diverse-select h-[30px] w-fit items-center gap-x-2 !flex"
              :hoverable="false"
              @click="handleTableCommand('add')"
            >
              <i-icons-table-add />
              添加存储目录
            </a-link>
          </template>
        </a-table>
      </a-form-item>

      <a-form-item
        label="单文件最大大小"
        field="disk_single_file_limit.value"
        hide-asterisk
        asterisk-position="end"
        required
        :rules="diskSingleFileLimitRules"
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>单文件最大大小</span>
            <span class="text-[#FA5566]">*</span>
            <a-tooltip
              :show-arrow="false"
              :content-style="{ 'max-width': '509px' }"
            >
              <i-icons-question class="question-icon" />
              <template #content>
                <span>允许存入磁盘缓存的单个文件大小。</span>
              </template>
            </a-tooltip>
          </div>
        </template>
        <a-input-number
          v-model="formState.disk_single_file_limit.value"
          :controls="true"
          :precision="0"
          :min="1"
          :max-length="13"
          class="cloud-input-number"
          hide-button
          placeholder="请输入单文件最大大小"
        >
          <template #append>
            <a-select
              :model-value="formState.disk_single_file_limit.unit"
              :options="diskFileSizeOptions"
              class="rounded-tl-none rounded-bl-none! border-none! bg-transparent!"
              @update:model-value="handleChangeFileSize"
            />
          </template>
        </a-input-number>
        <!-- <a-input-number v-model="formData.cache_size" :max-length="13" class="!w-100"  placeholder="请输入缓存最大容量">
            <template #append>
              <a-select v-model="diskFileSizeUnit" :options="diskOptions">
              </a-select>
            </template>
          </a-input-number> -->
      </a-form-item>

      <a-divider
        type="dashed"
        margin="0"
      />
      <div class="node-sub-title mb-4 mt-6">
        内存配置
      </div>

      <a-form-item
        label="最大容量"
        hide-asterisk
        required
        asterisk-position="end"
        field="memory_config.max_capacity.value"
        :rules="singleMaxCapacityRules"
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>最大容量</span>
            <span class="text-[#FA5566]">*</span>
            <a-tooltip
              :content-style="{ 'max-width': '509px' }"
              :show-arrow="false"
            >
              <i-icons-question class="question-icon text-#86909C" />
              <template #content>
                <span>
                  1.智能分配：根据磁盘已分配的总容量，按最优比例自动计算并分配内存（约10MB
                  RAM / 1GB 磁盘）。
                  <br>
                  2.手动分配：为内存指定固定容量。
                </span>
              </template>
            </a-tooltip>
          </div>
        </template>
        <div class="w-full">
          <div class="h-8">
            <a-radio-group
              v-model="formState.memory_config.mode"
              class="ml-2"
            >
              <a-radio :value="1">
                智能分配
              </a-radio>
              <a-radio :value="2">
                手动分配
              </a-radio>
            </a-radio-group>
          </div>

          <div v-if="formState.memory_config.mode === 2">
            <a-input-number
              v-model="formState.memory_config.max_capacity.value"
              :controls="true"
              :precision="0"
              :min="1"
              :max-length="13"
              class="cloud-input-number"
              hide-button
              placeholder="请输入最大容量"
            >
              <template #append>
                <a-select
                  v-model="formState.memory_config.max_capacity.unit"
                  :options="MaxSizeOptions"
                  class="rounded-tl-none rounded-bl-none! border-none! bg-transparent!"
                />
              </template>
            </a-input-number>
          </div>
        </div>
      </a-form-item>

      <a-form-item
        label="单文件最大大小"
        field="memory_config.single_file_limit.value"
        hide-asterisk
        asterisk-position="end"
        required
        :rules="singleFileLimitRules"
      >
        <template #label>
          <div class="flex items-center gap-x-1">
            <span>单文件最大大小</span>
            <span class="text-[#FA5566]">*</span>
            <a-tooltip
              :show-arrow="false"
              :content-style="{ 'max-width': '509px' }"
            >
              <i-icons-question class="question-icon" />
              <template #content>
                <span>允许存入内存缓存的单个文件大小。</span>
              </template>
            </a-tooltip>
          </div>
        </template>
        <a-input-number
          v-model="formState.memory_config.single_file_limit.value"
          :controls="true"
          :precision="0"
          :min="1"
          :max-length="13"
          class="cloud-input-number"
          hide-button
          placeholder="请输入单文件最大大小"
        >
          <template #append>
            <a-select
              v-model="formState.memory_config.single_file_limit.unit"
              :options="memoryFileSizeOptions"
              class="rounded-tl-none rounded-bl-none! border-none! bg-transparent!"
            />
          </template>
        </a-input-number>
        <!-- <a-input-number v-model="formData.cache_size" :max-length="13" class="!w-100"  placeholder="请输入缓存最大容量">
            <template #append>
              <a-select v-model="diskFileSizeUnit" :options="diskOptions">
              </a-select>
            </template>
          </a-input-number> -->
      </a-form-item>
    </a-form>
  </a-drawer>
</template>

<style lang="less" scoped>
:deep(.arco-input-outer > :first-child) {
  border-top-right-radius: 0px !important;
  border-bottom-right-radius: 0px !important;
}

:deep(.arco-form-item-label) {
  display: flex;
  width: 100%;
}

.arco-radio:first-child {
  padding-left: 0;
}

.question-icon {
  color: #86909c;
  width: 14px !important;
  height: 14px !important;
  cursor: pointer;

  &:hover {
    color: #00a65b;
  }
}

:deep(.arco-input-append) {
  background-color: #ffffff;
}

.node-sub-title {
  color: var(--text-1, #1d2129);
  font-size: 12px;
  font-style: normal;
  font-weight: 700;
  line-height: normal;
}

.node-ip-table {
  //border: 1px solid #dfe2e5;
  //@apply rounded-2 overflow-hidden;

  :deep(.arco-table-container) {
    border-radius: 8px 8px 0px 0px !important;
  }

  :deep(.arco-table-tr) {
    @apply !bg-#fff;
  }

  :deep(.arco-table-th) {
    @apply !bg-transparent;
  }

  :deep(.arco-table-footer) {
    //border-width: 0px !important;
    border-radius: 0px 0px 8px 8px !important;
    border: 1px solid #f0f5f5;
    border-top: none;
  }
}
</style>
